<?php

namespace App\Http\Services;

use App\Http\Repositories\Daos\Campus\CampusDao;
use App\Http\Traits\GlobalConstant;
use App\Models\CourseSection;
use App\Util\Helper;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class CampusService extends BaseService
{
    protected $campusDao;

    public function __construct(CampusDao $campusDao)
    {
        $this->campusDao = $campusDao;
    }

    public function lists()
    {
        $word      = request('key_word') ?? '';
        $lat       = request('lat') ?? 0;
        $lng       = request('lng') ?? 0;
        $condition = [
            'status' => 1,
        ];
        if (!empty($word)) {
            $condition[] = ['name', 'like', '%' . $word . '%'];
        }
        $page   = request('page') ?? 1;
        $size   = request('size') ?? 10;
        $offset = ($page * $size) - $size;
//        $field  = ['*'];
        $list = $this->campusDao->getModel()->where($condition)
            ->limit($size)->offset($offset)
            ->select(DB::raw("*,(6371 * acos(cos(radians(latitude)) * cos(radians($lat)) * cos(radians(longitude) - radians($lng)) + sin(radians(latitude)) * sin(radians($lat))))*1000 AS distance"))
//            ->withCount(["courseMany", "courseCanEnrollMany"])->orderBy('distance', 'asc')->get()->toArray();
            ->withCount(["courseMany"])->orderBy('distance', 'asc')->get()->toArray();
        if (!empty($list)) {
            foreach ($list as &$item) {
                $item['course_can_enroll_many_count'] = DB::table('course')->where('campus_id', $item['id'])
                    ->whereIn('id', function ($query) {
                        $query->select('course_id')->from('course_section')->groupBy('course_id')->havingRaw('min(begin_time) > ?', [time()]);
                    })->count();
            }
            unset($item);
        }
        $total = $this->campusDao->getModel()->where($condition)->count();
        return compact("list", "total");
    }

    public function markerLists2()
    {
        $word      = request('key_word') ?? '';
        $cate      = request('category') ?? '';
        $lat       = request('lat') ?? 0;
        $lng       = request('lng') ?? 0;
        $condition = [
            'status' => 1,
//            'total'      => ['symbol' => '>', 'val' => 0],
        ];
        if (!empty($word)) {
            $condition[] = ['name', 'like', '%' . $word . '%'];
        }
        if (!empty($cate)) {
            $condition['type'] = $cate;
        }
//        $field = ['*'];
        $list = $this->campusDao->getModel()->where($condition)->orderBy('created_at', 'asc')
            ->select(DB::raw("id,name,address,logo,longitude,latitude,(6371 * acos(cos(radians(latitude)) * cos(radians($lat)) * cos(radians(longitude) - radians($lng)) + sin(radians(latitude)) * sin(radians($lat))))*1000 AS distance"))
            ->orderBy('distance', 'asc')->get()->toArray();
        $arr  = [];
        if ($list) {
//            foreach ($list as &$item) {
//                $item['width']    = 128;
//                $item['height']   = 85;
//                $item['iconPath'] = '/static/temp/pos.png';
//                $item['label']    = GlobalConstant::setMarkerLabel($item['name']);
//                $item['pri']      = $item['id'];
//                $item['id']       = (int)(Helper::randString(4, 1) . $item['id']);
//                $temp             = $item;
//                $temp['id']       = (int)(Helper::randString(4, 1) . $temp['pri']);
//                $temp['label']    = GlobalConstant::setMarkerLabel2($temp['address']);
//                $arr[]            = $temp;
//            }
            foreach ($list as &$item) {
//                $item['width']    = 128;
//                $item['height']   = 85;
                $item['width']    = 48;
                $item['height']   = 48;
                $item['iconPath'] = '/static/temp/address.png';
                $item['label']    = GlobalConstant::newSetMarkerLabel($item['name']);
                $item['pri']      = $item['id'];
                $item['id']       = (int)(Helper::randString(4, 1) . $item['id']);
                $temp             = $item;
                $temp['id']       = (int)(Helper::randString(4, 1) . $temp['pri']);
//                $temp['label']    = GlobalConstant::newSetMarkerLabel2($temp['address']);
                $arr[] = $temp;
            }
            unset($item);
            $list = array_merge($arr, $list);
        }
        return $list;
    }

    public function markerLists()
    {
        Log::info('请求时间'.time());
        $word      = request('key_word') ?? '';
        $cate      = request('category') ?? '';
        $lat       = request('lat') ?? 0;
        $lng       = request('lng') ?? 0;
        $campusId  = request('campus_id') ?? 0;
        $condition = [
            'status' => 1,
//            'total'      => ['symbol' => '>', 'val' => 0],
        ];
        if (!empty($word)) {
            $condition[] = ['name', 'like', '%' . $word . '%'];
        }
        if (!empty($cate)) {
            $condition['type'] = $cate;
        }
        $query = $this->campusDao->getModel()->where($condition)->orderBy('created_at', 'asc')
            ->select(DB::raw("id,name,address,logo,longitude,latitude,(6371 * acos(cos(radians(latitude)) * cos(radians($lat)) * cos(radians(longitude) - radians($lng)) + sin(radians(latitude)) * sin(radians($lat))))*1000 AS distance"))
            ->orderBy('distance', 'asc');
        if (!empty($campusId)) {
            $query = $query->where('id', $campusId);
        } else {
            $query = $query->having('distance', '<', 4000);
        }
        $list = $query->get()->toArray();

        $arr = [];
        if ($list) {
//            foreach ($list as &$item) {
//                $item['width']    = 128;
//                $item['height']   = 85;
//                $item['iconPath'] = '/static/temp/pos.png';
//                $item['label']    = GlobalConstant::setMarkerLabel($item['name']);
//                $item['pri']      = $item['id'];
//                $item['id']       = (int)(Helper::randString(4, 1) . $item['id']);
//                $temp             = $item;
//                $temp['id']       = (int)(Helper::randString(4, 1) . $temp['pri']);
//                $temp['label']    = GlobalConstant::setMarkerLabel2($temp['address']);
//                $arr[]            = $temp;
//            }
            foreach ($list as &$item) {
                $item['width']    = 24;
                $item['height']   = 24;
                $item['iconPath'] = '/static/temp/address.png';
                $item['label']    = GlobalConstant::newSetMarkerLabel($item['name']);
                $item['pri']      = $item['id'];
                $item['id']       = (int)(Helper::randString(4, 1) . $item['id']);
                $temp             = $item;
                $temp['id']       = (int)(Helper::randString(4, 1) . $temp['pri']);
//                $temp['label']    = GlobalConstant::newSetMarkerLabel2($temp['address']);
                $arr[] = $temp;
            }
            unset($item);
            $list = array_merge($arr, $list);
        }
        return $list;
    }


    public static function searchCategoryList()
    {
        return GlobalConstant::getSearchCategoryMap();
    }

    public function detail()
    {
        $id = request('campus_id') ?? 0;
        return $this->campusDao->getOne(['id' => $id]);
    }

}
